package com.xone.xapp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONObject;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

public class AutoCompleteListAdapter extends
		BasicListAdapter<AutoCompleteListHolder> implements Filterable {
	protected Context context;
	protected LayoutInflater mInflater;
	protected String saleType;

	public AutoCompleteListAdapter(Context context, String saleType) {
		this.context = context;
		this.saleType = saleType;
		this.mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public View getView(int position, View view, ViewGroup parent) {
		ViewHolder viewHolder;
		if (null == view) {
			viewHolder = new ViewHolder();
			view = this.mInflater
					.inflate(R.layout.auto_complete_listview, null);
			viewHolder.setTextView((TextView) view
					.findViewById(R.id.auto_complete_item));
			view.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) view.getTag();
		}
		AutoCompleteListHolder holder = list.get(position);
		viewHolder.getTextView().setText(holder.getName());
		return view;
	}

	/**
	 * 把JSON列表对象转化为系统中的对应模型对象
	 */
	@Override
	public List<AutoCompleteListHolder> initWithJsonList(List<JSONObject> list) {
		// 判断对象如果是空或者为null，则直接返回空列表
		if (JSONUtils.isNullOrEmptyList(list)) {
			return Collections.emptyList();
		}
		if (null == this.list) {
			this.list = new ArrayList<AutoCompleteListHolder>(); 
		} else {
			this.list.clear();
		}
		for (int i = 0; i < list.size(); i++) {
			this.list.add(new AutoCompleteListHolder(list.get(i), saleType));
		}
		for (AutoCompleteListHolder h : this.list) {
			System.out.println("AutoCompleteListHolder:" + h.getName());
		}
		return this.list;
	}

	@Override
	public int getTopLastIndex() {
		return -1;
	}

	protected class ViewHolder {
		protected TextView textView;
		public TextView getTextView() {
			return textView;
		}
		public void setTextView(TextView textView) {
			this.textView = textView;
		}
	}

	@Override
	public Filter getFilter() {
		return new Filter() {
			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
				FilterResults results = new FilterResults();
				if (list == null) {
					list = new ArrayList<AutoCompleteListHolder>();
				}
				results.values = list;
				results.count = list.size();
				return results;
			}
			@Override
			protected void publishResults(CharSequence constraint,
					FilterResults results) {
				if (null != results && results.count > 0) {
					notifyDataSetChanged();
				} else {
					notifyDataSetInvalidated();
				}
			}
		};
	}

}
